import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../manger/global_config.dart';
import '../../services/yh_info_manger.dart';
import '../view/coupon_list_item.dart';
import '../../models/yh_info_model.dart';
import '../../main.dart';
import '../../components/custom_flied_dialog.dart';
import '../../components/toast_utils.dart';
import '../../manger/network_utils.dart';

class MyCouponPage extends StatefulWidget {
  const MyCouponPage({super.key});

  @override
  State<MyCouponPage> createState() => _MyCouponPageState();
}

class _MyCouponPageState extends State<MyCouponPage> {
  int _selectedIndex = 0;
  List<CouponListModel> _myCoupon = [];

  @override
  void initState() {
    super.initState();
    _loadCouponData(_selectedIndex);
  }

  void _showLogoutDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => FieldDialog(
        title: AppLocalizations.of(context)!.redeemCoupon,
        description: AppLocalizations.of(context)!.enterCouponCode,
        leftButtonText: AppLocalizations.of(context)!.cancel,
        rightButtonText: AppLocalizations.of(context)!.redeemNow,
        onLeftPressed: () => Navigator.pop(context),
        onRightPressed: (value) {
          Navigator.pop(context);
          _voucherCode(value);
        },
        
      ),
    );
  }

  Future<void> _voucherCode(String text) async {
    ToastUtils.showLoadingToast(context);
    try {
      final response = await NetworkUtils.post(
        RequestCmd.voucherCode,
        body: {"voucherCode": text},
      );
      ToastUtils.dismissLoadingToast();

      if (response['code'] == 200) {
        ToastUtils.showCenterToast(context, response['msg']);
        _loadCouponData(_selectedIndex);
      } else {
        ToastUtils.showCenterToast(context, response['msg']);
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
    }
  }

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;

    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 40,
        title: Text(localizations.coupon, style: const TextStyle(fontSize: 17)),
      ),
      body: Column(
        children: [
          _buildCouponTabBar(context),
          Expanded(
            child: _buildCouponList(context),
          ),
        ],
      ),
      bottomNavigationBar: Container(
        height: 85,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(top: BorderSide(color: Colors.grey.withValues(alpha: 0.2))),
        ),
        child: Row(
          children: [
            Expanded(
              child: Container(
                padding: const EdgeInsets.only(right: 10),
                child: Text(
                  localizations.existingCouponCode,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.black,
                    fontSize: 13,
                  ),
                ),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                // 兑换按钮点击事件
                _showLogoutDialog(context);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: GlobalConfig.titleBlueColor,
                minimumSize: const Size(90, 36),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(18),
                ),
              ),
              child: Text(
                localizations.redeemNow,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                ),
              ),
            ),
          ],
        )
      ),
    );
  }

  Widget _buildCouponTabBar(BuildContext context) {
    final localizations = AppLocalizations.of(context)!;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
      decoration: BoxDecoration(
        color: GlobalConfig.titleBlueColor,
        borderRadius: BorderRadius.circular(17),
      ),
      height: 34,
      child: Row(
        children: List.generate(3, (index) {
          final isSelected = index == _selectedIndex;
          final title = _getTabTitle(index, localizations);

          return Expanded(
            child: GestureDetector(
              onTap: () {
                if (_selectedIndex != index) {
                  setState(() => _selectedIndex = index);
                  _loadCouponData(index);
                }
              },
              child: Container(
                margin: const EdgeInsets.all(2),
                decoration: BoxDecoration(
                  color: isSelected ? Colors.white : Colors.transparent,
                  borderRadius: BorderRadius.circular(15),
                ),
                alignment: Alignment.center,
                child: Text(
                  title,
                  style: TextStyle(
                    color: isSelected ? GlobalConfig.titleBlueColor : Colors.white,
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ),
          );
        }),
      ),
    );
  }

  String _getTabTitle(int index, AppLocalizations localizations) {
    switch (index) {
      case 0:
        return _myCoupon.isNotEmpty
            ? '${localizations.notUsed}(${_myCoupon.length})'
            : localizations.notUsed;
      case 1:
        return localizations.used;
      case 2:
        return localizations.expireds;
      default:
        return '';
    }
  }

  Widget _buildCouponList(BuildContext context) {
    if (_myCoupon.isEmpty) {
      return Center(
        child: Text(
          AppLocalizations.of(context)!.none + AppLocalizations.of(context)!.cavailable,
          style: TextStyle(color: Colors.grey, fontSize: 15),
        ),
      );
    }

    return ListView.builder(
      itemCount: _myCoupon.length,
      itemBuilder: (context, index) {
        return CouponListItem(
          coupon: _myCoupon[index],
          index: _selectedIndex,
          onUsePressed: () {
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(builder: (context) => const MainPage()),
              (route) => false,
            );
          },
        );
      },
    );
  }

  Future<void> _loadCouponData(int index) async {
    final result = await MyCouponManger().loadDiscountData(index);
    if (mounted) {
      setState(() {
        _myCoupon = result.success && result.myCoupon != null
            ? result.myCoupon!
            : [];
      });
    }
  }
}
